<?php

namespace app\admin\controller;

use app\admin\model\ExamQuestion as ExamQuestionModel;
use app\admin\validate\ExamQuestion as ExamQuestionValidate;
use think\facade\Validate;
use think\facade\Request;
use think\facade\Db;

use app\common\controller\Backend;

class ExamQuestion extends Backend
{
    // 题库列表
    public function index(): void
    {
        $type = $this->request->get('type', '');
        $search = trim($this->request->get('search', ''));
        $where = [];
        if ($type) {
            $where[] = ['type', '=', $type];
        }

        $query = ExamQuestionModel::where($where);
        if ($search !== '') {
            $like = '%' . $search . '%';
            $query = $query->where(function ($q) use ($like) {
                $q->where('content', 'like', $like)
                    ->whereOr('analysis', 'like', $like)
                    ->whereOr('options', 'like', $like);
            });
        }

        $list = $query->order('id desc')->paginate(20);

        $this->success('', $list);
    }

    // 新增题目
    public function add(): void
    {
        $data = $this->request->post();
        $validate = new ExamQuestionValidate();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $data['create_time'] = time();
        $data['update_time'] = time();
        ExamQuestionModel::create($data);
        $this->success('添加成功');
    }

    // 编辑题目
    public function edit(): void
    {
        $id = $this->request->post('id');
        $data = $this->request->post();
        $validate = new ExamQuestionValidate();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $data['update_time'] = time();
        ExamQuestionModel::update($data, ['id' => $id]);
        $this->success('修改成功');
    }

    // 删除题目
    public function del(): void
    {
        $ids = $this->request->post('ids');
        if (!$ids) {
            $this->error('参数错误');
        }
        ExamQuestionModel::destroy($ids);
        $this->success('删除成功');
    }

    // 题目详情
    public function detail($id)
    {
        $info = ExamQuestionModel::find($id);
        if (!$info) {
            return json(['code' => 0, 'msg' => '题目不存在']);
        }
        return json(['code' => 1, 'msg' => '', 'data' => $info]);
    }
}
